package math;

/**
 * O(logn) 时间复杂度获取斐波那契的某一项
 * @author Liaorun
 */
public class ZeroLeftOneStringNumber {

    public static int fi(int n) {
        // 斐波那契没有小于1的项
        if (n < 1) {
            return 0;
        }

        // 斐波那契前两项为1
        if (n == 1 || n == 2) {
            return 1;
        }

        int[][] base = {{1, 1}, {1, 0}};

        int[][] res = matrixPower(base, n - 2);

        return res[0][0] + res[1][0];
    }

    private static int[][] matrixPower(int[][] m, int p) {
        int[][] res = new int[m.length][m[0].length];

        // res 初始化为单位矩阵，只有左上到右下的对角线上是1
        for (int i = 0; i < res.length; i++) {
            res[i][i] = 1;
        }

        int[][] t = m;
        for (; p != 0; p >>= 1) {
            // 右移一位后不为0
            if ((p & 1) != 0) {
                // 最低位为1,
                res = muliMatrix(res, t);
            }

            // base = base * base
            t = muliMatrix(t, t);
        }
        return res;
    }

    /**
     * 矩阵相乘
     *
     * @param m1 矩阵
     * @param m2 矩阵
     * @return 相乘的结果
     */
    private static int[][] muliMatrix(int[][] m1, int[][] m2) {
        int[][] res = new int[m1.length][m2[0].length];
        for (int i = 0; i < m1.length; i++) {
            for (int j = 0; j < m2[0].length; j++) {
                for (int k = 0; k < m2.length; k++) {
                    res[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }

        return res;
    }
}
